#include "mylog.h"

#include <QFile>
#include <QTextStream>
#include <QDateTime>
#include <QDate>
#include <QTime>
#include <QDir>

namespace AppLog {
    extern QString dateStr;
    extern QString timeStr;
}

void AppLog::initLog()
{
    AppLog::dateStr = QDate::currentDate().toString("yyyy-MM-dd");
    AppLog::timeStr = QTime::currentTime().toString("hh-mm");
    QString _dir_p = getLogDir();
    QDir _dir;
    _dir.mkdir(_dir_p);
};

void AppLog::logMsgHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QByteArray localMsg = msg.toLocal8Bit();
    QString typeStr = "InfoMsg";
    switch (type) {
        case QtDebugMsg:
            typeStr = "Debug";
            break;
        case QtWarningMsg:
            typeStr = "Warn";
            break;
        case QtCriticalMsg:
            typeStr = "Critical";
            break;
        case QtFatalMsg:
            typeStr = "Fatal";
            break;
        default:
            break;
    }
    QString strLog = QString(QDateTime::currentDateTime().toString("yyyy/MM/dd hh:mm:ss ")+"[%1] %2 (%3:%4,%5)")
                .arg(typeStr).arg(localMsg.constData()).arg(context.file).arg(context.line).arg(context.function);
    QFile outFile(getLogFile());
    outFile.open(QIODevice::WriteOnly | QIODevice::Append);

    /**< the max size of log.txt.*/
    if(outFile.size()>LOGFILEMAX)
    {
        outFile.close();
        AppLog::timeStr = QTime::currentTime().toString("hh-mm");
//        outFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Truncate);
//        outFile.close();
        outFile.setFileName(getLogFile());
        outFile.open(QIODevice::WriteOnly | QIODevice::Append);
    }

    QTextStream ts(&outFile);
    ts << strLog << endl;
};

QString AppLog::getLogFile()
{
    QString _dir = getLogDir();
#ifdef WIN32
    _dir+="\\";
#else
    _dir+="/";
#endif
    if(QDate::currentDate().toString("yyyy-MM-dd")!=AppLog::dateStr){
        AppLog::dateStr=QDate::currentDate().toString("yyyy-MM-dd");
        AppLog::timeStr = QTime::currentTime().toString("hh-mm");
    }
    return _dir+AppLog::dateStr+"_"+AppLog::timeStr+QString("_gatherContol.log");
};

QString AppLog::getLogDir()
{
    QString _dir = QString("log");
#ifdef ANDROID
    _dir = QString("/storage/emulated/0/GatherControl/log");
#endif
    return _dir;
};

